package top.surgeqi.security.demo.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import top.surgeqi.security.demo.bean.result.Result;
import top.surgeqi.security.demo.constants.SecurityError;
import top.surgeqi.security.jwt.contants.AuthConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p><em>Created by qipp on 2020/7/1 14:27</em></p>
 * 登录过期/未登录处理器
 *
 * @author <a href="https://gitee.com/qipengpai">qipp</a>
 * @since 1.0.1
 */
@Component
public class LoginExpireHandler implements AuthenticationEntryPoint {

    /**
     * springmvc启动时自动装配json处理类
     */
    private final ObjectMapper objectMapper;

    public LoginExpireHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(AuthConstants.CONTENT_TYPE);
        // 登录过期/用户未登录
        Result<Object> result = Result.failed(SecurityError.USER_NOT_LOGGED_IN.getResCode(), SecurityError.USER_NOT_LOGGED_IN.getResMsg());
        response.getWriter().write(objectMapper.writeValueAsString(result));
        response.getWriter().flush();
        response.getWriter().close();
    }
}

